<?php
/**
 * author  :  hation
 *  email  : 331596350@qq.com
 */
namespace App\Http\Controllers\DepartmentManagement;

use App\Models\Admin;
use App\Models\Product;
use App\Models\Progress;
use Request;
use Session;
use Redirect;
use App\Http\Controllers\CommonController;
use DB;
class FinanceManagementController extends CommonController
{
    protected $pageNum=15;
    public function __construct()
    {
         parent::__construct();
    }
    /**
     * 登录界面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        return view('departmentManagement/finance/login');
    }
    public function loginOut()
    {
        session()->flush();
        return Redirect::to('management/finance/login');
    }
    /**
     * 登录处理逻辑
     * @return string
     */
    public function doLogin()
    {
        $request=Request::all();
        $params['account']=$request['account'];
        $params['password']=md5($request['password']);
        $params['type']=config('config.management_flag.finance');
        $re=Admin::where($params)->first();
        if(!empty(collect($re)->toArray())){
            Session::put('fid', $re['id']);
            Session::put('fname', $re['real_name']);
            Session::put('real_name', $re['real_name']);
            return Redirect::to('management/finance/index');
        }else{
            return error_return("登录失败");
        }
    }
    /**
     * 财务部管理员首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $product=Progress::with(['FirstType','Product','ProgressList'])
            ->whereNotIn('claim_state',[config('config.claim_state.init')])
            ->whereNotIn('business_state',[config('config.business_progress.wait_set_payment')])
            ->orderBy('finance_state','asc')
            ->orderBy('updated_at','desc')
            ->paginate($this->pageNum);
        $config=config('config.finance_progress');
        $map=config('config.operation_progress.finance');
        $count=$this->getNum();
        $data=['product','config','map','count'];
       // dump($product);exit;
        return view('departmentManagement/finance/index',compact($data));
    }
//    public function indexSearch()
//    {
//        $request = Request::all();
//        $keywords="";
//        if (isset($request['search'])) {
//            $keywords = $request['search'];
//        }
//        $product=Progress::with(['FirstType','Product','ProgressList'])
//            ->whereNotIn('claim_state',[config('config.claim_state.init')])
//            ->whereNotIn('business_state',[config('config.business_progress.wait_set_payment')])
//            ->orderBy('finance_state','asc')
//            ->orderBy('updated_at','desc')
//            ->paginate(0);
//        $config=config('config.finance_progress');
//        $map=config('config.operation_progress.finance');
//        $count=$this->getNum();
//        $data=['product','config','map','count','keywords'];
//        // dump($product);exit;
//        return view('departmentManagement/finance/indexSearch',compact($data));
//    }

    public function indexCertainSearch()
    {
        $company = Request::input('company');
        $is_renew= Request::input('is_renew');
        $first_type= Request::input('first_type');
        $applicant= Request::input('applicant');
        $created_at= Request::input('created_at');
        $name= Request::input('name');
        $product=Progress::with(['FirstType','Product','ProgressList'])
            ->join('product','product.id','=','progress.product_id')
            ->whereNotIn('claim_state',[config('config.claim_state.init')])
            ->whereNotIn('business_state',[config('config.business_progress.wait_set_payment')])
            ->when($company, function ($query) use ($company) {
                return $query->where('product.company', $company);
            })
            ->when($is_renew, function ($query) use ($is_renew) {
                return $query->where('progress.is_renew', $is_renew);
            })
            ->when($name, function ($query) use ($name) {
                return $query->where('product.name', $name);
            })
            ->when($first_type, function ($query) use ($first_type) {
                return $query->where('product.first_type_id', $first_type);
            })
            ->when($applicant, function ($query) use ($applicant) {
                return $query->where('product.applicant', $applicant);
            })
            ->when($created_at, function ($query) use ($created_at) {
                return $query->where('progress.created_at','like','%'.$created_at.'%');
            })
            ->orderBy('progress.finance_state','asc')
            ->orderBy('progress.updated_at','desc')
            ->paginate(0);
        //dd($product);
        $config=config('config.finance_progress');
        $map=config('config.operation_progress.finance');
        $count=$this->getNum();
        $data=['product','config','map','count'];
        // dump($product);exit;
        return view('departmentManagement/finance/indexSearch',compact($data));
    }
    public function getNum()
    {
        $count=[0,0,0,0];
        $product=Progress::all();
        foreach ($product as $v){
            if (!empty($v['price'])&&empty($v['first_pay_time'])){
                $count[0]++;
            }elseif(!empty($v['price'])&&!empty($v['first_pay_time'])){
                $count[1]++;
                if (!empty($v['tail_pay_time'])){
                    if($this->checkNum($v['price'])){
                        $count[2]+=(float)$v['price'];
                    }
                }else{
                    if($this->checkNum($v['first_payment'])){
                        $count[2]+=(float)$v['first_payment'];
                    }
                }
            }
            if(!empty($v['price'])&&$this->checkNum($v['price'])){
                $count[3]+=(float)$v['price'];
            }
        }
        $count[3]=priceFormat($count[3]);
        $count[2]=priceFormat($count[2]);
        return $count;
    }

    public function operation($pid,$id,$state)
    {
        $date=date('Y-m-d H:i:s');
        $params['finance_state']=((int)$state+1);
        if(!in_array($params['finance_state'],array_values(config('config.finance_progress')))){
            return error_return("更新失败");
        }
        if(empty(Session::get('fname'))){
            return Redirect::to('management/finance/login');
        }

        $params['agent']='财务部-'.Session::get('fname');
        $params1['updated_at']=$date;
        $params['updated_at']=$date;
        $item1=Product::find($id);
        $item=Progress::find($pid);

        if(empty($item)||empty($item1)){
            return error_return("暂无该条记录");
        }
        if($item['is_cancel']==config('config.mission_state_map.cancel')){
            return error_return("任务已被取消，不能操作");
        }
        if($params['finance_state']==config('config.finance_progress.ensure_first_payment')){
            $params['state']=config('config.product_state_map.unsettled');
            if($item['tail_payment']=='0'){
                if(empty($item['first_pay_time'])) {
                    $item['first_pay_time'] = $date;
                    $item['tail_pay_time'] = $date;
                    $item['first'] = 1;
                    $item['tail'] = 1;
                }
                $params['finance_state']++;
            }else{
                $item['first_pay_time']=$date;
                $item['first']=1;
            }
            if(empty($item1['file'])){
                $params['business_state']=config('config.business_progress.first_pay_no_upload');
            }else{
                $params['business_state']=config('config.business_progress.first_pay_upload');
            }
        }
        if($params['finance_state']==config('config.finance_progress.ensure_tail_payment')){
            if(empty($item['tail_pay_time'])){
                $item['tail_pay_time'] = $date;
                $item['tail'] = 1;
            }
        }
        foreach ($params as $k=> $v){
            $item[$k]=$v;
        }
        foreach ($params1 as $k=> $v){
            $item1[$k]=$v;
        }
        if($item1->save()&&$item->save()&&!empty(Session::get('fid'))){
            $d['product_id']=$id;
            $d['operator_id']=Session::get('fid');
            $d['operator_type']=config('config.operation_role.admin');
            $d['content']=config('config.operation_progress.finance')[$state];
            $d['operator_name']='财务部-'.Session::get('fname');
            $d["process_id"]=$item[ 'id' ];
            $d["progress_list_id"]=$item[ 'progress_list_id' ];
            addOperation($d);
            return success_return('更新成功');
        }else{
            return error_return("更新失败");
        }
    }
    public function userInfo(){
        $uid=Session::get('fid');
        $data=object_to_array(
            DB::table('admin')->where(array('id'=>$uid))->first()
        );
//        dump($data);exit();
        return view('departmentManagement/finance/userInfo')->with('data',$data);
    }
    public function changePassword(){
        $uid=Session::get('fid');
        $pwd=object_to_array(DB::table('admin')->where(array("id"=>$uid))->first());
//        dump($pwd['password']);exit();
        return view('departmentManagement/finance/changePassword')->with('data',$pwd['password']);
    }
    public function doChangePassword(){
        $uid=Session::get('fid');
        $input=Request::all();
        if(empty($input['old_pwd'])){
            return back()->with('error','旧密码为空');
        }elseif (empty($input['new_pwd'])){
            return back()->with('error','新密码为空');
        }elseif (empty($input['require_pwd'])){
            return back()->with('error','确认密码为空');
        }else{
            $data['password']=md5($input['require_pwd']);
            $res=DB::table('admin')->where(array("id"=>$uid))->update($data);
            if($res){
                return back()->with('success','密码修改成功');
            }else{
                return back()->with('error','修改失败，请联系管理员');
            }
        }
    }
    /**
     * 校验是否是合法的非负浮点数
     * @param $num string 需要检验的串
     * @return int 1 yes 0 no
     */
    protected function checkNum($num){
        return preg_match("/^\d+(\.\d+)?$/",$num);
    }
}
